# -*- coding: utf-8 -*-
__author__ = 'ranzechen'
__time__ = 2019 / 1 / 11
__function__ = ''


import os
import utils
import getpass
import qrcode as qd
from PIL import Image
from PyQt5 import QtWidgets,QtGui
from PyQt5.QtWidgets import QFileDialog,QMessageBox
from uic.toolkit import Ui_MainWindow

class qrcode(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(qrcode, self).__init__()
        self.setupUi(self)

    def qr_make_fun(self):
        rongcuo_str = self.qr_rongcuo_combobox.currentText()
        rongcuo_dict = {"7%":qd.ERROR_CORRECT_L,"15%":qd.ERROR_CORRECT_M,"30%":qd.ERROR_CORRECT_H}
        rongcuo_res = rongcuo_dict.get(rongcuo_str)
        xiangsu_dict = {"259px":"7","148px":"4","185px":"5","222px":"6","296px":"8","333px":"9","370px":"10","407px":"11"}
        xiangsu_str = self.qr_xiangsu_combobox.currentText()
        xiangsu_res = xiangsu_dict.get(xiangsu_str)
        size_dict = {"164px":"4","180px":"5","196px":"6","212px":"7","228px":"8","244px":"9","260px":"10","292px":"12","324px":"14","356px":"16"}
        size_str = self.qr_size_combobox.currentText()
        size_res = size_dict.get(size_str)
        border_dict = {"4px":"4","5px":"5","6px":"6","7px":"7","8px":"8","9px":"9","10px":"10","11px":"11","12px":"12"}
        border_str = self.qr_border_combobox.currentText()
        border_res = border_dict.get(border_str)

        input_str = self.qr_input_text.toPlainText()
        web_str = self.qr_web_text.text()
        if (len(input_str.strip()) != 0 and len(web_str.strip()) == 0) or (len(input_str.strip()) == 0 and len(web_str.strip()) != 0):
            # 判断是否有logo图片
            if os.path.exists(r'resources/others/qr_logo_tmp.png'):
                # 区分是web输入还是文本框输入
                if len(input_str.strip()) != 0:
                    qrcode.make_qr_logo(self,version=size_res,box_size=xiangsu_res,border=border_res,text=input_str)
                else:
                    if 'http' in web_str or 'https' in web_str:
                        qrcode.make_qr_logo(self, version=size_res, box_size=xiangsu_res,border=border_res, text=web_str)
                    else:
                        qrcode.make_qr_logo(self, version=size_res,box_size=xiangsu_res,border=border_res, text='http://%s' % web_str)
            else:
                if len(input_str.strip()) != 0:
                    qrcode.make_qr_no_logo(self,version=size_res,error_corr=rongcuo_res,box_size=xiangsu_res,border=border_res,text=input_str)
                else:
                    if 'http' in web_str or 'https' in web_str:
                        qrcode.make_qr_no_logo(self, version=size_res, error_corr=rongcuo_res, box_size=xiangsu_res,border=border_res, text=web_str)
                    else:
                        qrcode.make_qr_no_logo(self, version=size_res, error_corr=rongcuo_res, box_size=xiangsu_res,border=border_res, text='http://%s' % web_str)

        else:
            utils.utils.tips_box(self,QMessageBox.Warning,'错误提示','请输入文本内容或者网址！')

    def qr_download_fun(self):
        win_username = getpass.getuser()
        image_download_path, image_type = QFileDialog.getSaveFileName(self, "保存图片",r"C:\Users\%s\Downloads\save" % win_username,"*.png")
        if len(str(image_download_path).strip()) != 0 and os.path.exists(r'resources/others/qr_code.png'):
            with open(image_download_path, 'wb') as fout:
                with open(r'resources/others/qr_code.png', 'rb') as fin:
                    fout.write(fin.read())
                fin.close()
            fout.close()
        if os.path.exists(image_download_path):
            utils.utils.tips_box(self, QMessageBox.Warning, '提示', '下载成功！')

    # logo图片上传
    def qr_logo_upload_fun(self):
        win_username = utils.utils.get_win_username(self)
        image_upload_path, image_upload_type = QFileDialog.getOpenFileName(self, "选择文件", r"C:\Users\%s\Desktop" % win_username,"*.jpg;;*.png;;*.jpeg;;*.bmp;;*.ico")
        if len(str(image_upload_path).strip()) != 0:
            with open(r'resources/others/qr_logo_tmp.png', 'wb') as fout:
                with open(image_upload_path, 'rb') as fin:
                    fout.write(fin.read())
                fin.close()
            fout.close()
        if os.path.exists(r'resources/others/qr_logo_tmp.png'):
            self.qr_logo_tips_label.setText('提示：LOGO图片上传成功！')


    # 删除logo图片
    def qr_logo_delete_fun(self):
        qr_tmp_path = r'resources/others/qr_logo_tmp.png'
        if os.path.exists(qr_tmp_path):
            os.remove(qr_tmp_path)
            if os.path.exists(r'resources/others/qr_logo_tmp.png'):
                self.qr_logo_tips_label.setText('提示：LOGO图片移除成功！')
            else:
                self.qr_logo_tips_label.setText('提示：LOGO图片移除成功！')
        else:
            self.qr_logo_tips_label.setText('提示：LOGO图片不存在！')

    # 生成没有logo的二维码
    def make_qr_no_logo(self,version,error_corr,box_size,border,text):
        try:
            qr = qd.QRCode(version=version, error_correction=error_corr, box_size=box_size, border=border)
            qr.add_data(text)
            qr.make(fit=True)
            img = qr.make_image()
            img = img.convert("RGBA")
            img.save(r'resources/others/qr_code.png')
            jpg = QtGui.QPixmap(r'resources/others/qr_code.png').scaled(self.qr_show_label.width()-15,self.qr_show_label.height()-15)
            self.qr_show_label.setPixmap(jpg)
        except Exception as e:
            utils.utils.tips_box(self,QMessageBox.Warning,'错误提示',str(e))

    # 生成带有logo的二维码
    def make_qr_logo(self,version,box_size,border,text):
        try:
            qr = qd.QRCode(version=version, error_correction=qd.ERROR_CORRECT_H, box_size=box_size, border=border)
            qr.add_data(text)
            qr.make(fit=True)
            img = qr.make_image()
            img = img.convert("RGBA")
            pic = Image.open(r"resources/others/qr_logo_tmp.png")
            img_w, img_h = img.size
            factor = 4
            size_w = int(img_w / factor)
            size_h = int(img_h / factor)
            icon_w, icon_h = pic.size
            if icon_w > size_w:
                icon_w = size_w
            if icon_h > size_h:
                icon_h = size_h
            qr_pic = pic.resize((icon_w, icon_h), Image.ANTIALIAS)
            w = int((img_w - icon_w) / 2)
            h = int((img_h - icon_h) / 2)
            pic_res = qr_pic.convert("RGBA")
            img.paste(pic_res, (w, h), pic_res)
            img.save(r'resources/others/qr_code.png')
            jpg = QtGui.QPixmap(r'resources/others/qr_code.png').scaled(self.qr_show_label.width() - 15,self.qr_show_label.height()-15)
            self.qr_show_label.setPixmap(jpg)
        except Exception as e:
            utils.utils.tips_box(self, QMessageBox.Warning, '错误提示', str(e))

    def show_qr_combobox_fun(self):
        rongcuo_combobox_list = ['7%', '15%', '30%']
        for i, ele in enumerate(rongcuo_combobox_list):
            self.qr_rongcuo_combobox.insertItem(i, ele)
        border_combobox_list = ['4px','5px','6px','7px','8px','9px','10px','11px','12px']
        for i, ele in enumerate(border_combobox_list):
            self.qr_border_combobox.insertItem(i, ele)
        #7，4，5，6，8，9，10，11
        xiangsu_combobox_list = ['259px','148px','185px','222px','296px','333px','370px','407px']
        for i, ele in enumerate(xiangsu_combobox_list):
            self.qr_xiangsu_combobox.insertItem(i, ele)
        #4,5,6,7,8,9,10,12,14,16
        size_combobox_list = ['164px','180px','196px','212px','228px','244px','260px','292px','324px','356px']
        for i, ele in enumerate(size_combobox_list):
            self.qr_size_combobox.insertItem(i, ele)